<template>
  <div id="storePriceTagIndex" :style="{ '--color': `${themeColor}` }">
    <c-title :hide="false" text="自助买单"></c-title>
    <div class="scanCode">
      <div class="storeDetail" v-if="storeInfo.store_info">
        <img :src="storeInfo.store_info.store_thumb" alt="" />
        <div class="storeName">{{ storeInfo.store_info.store_name }}</div>
      </div>
      <div class="codeImg" @click="toScanCode">
        <div class="codeImgBox">
          <img src="https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/storePriceTag%2Fcode.png" alt="" />
        </div>
        <div class="txt">请扫码签码或条形码</div>
      </div>
    </div>
    <div class="shoplistHead">
      <div class="left">我的商品列表</div>
      <div class="right" @click="clearCart">
        <img src="https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/storePriceTag%2Fdelete.png" alt="" />
        全部清空
      </div>
    </div>
    <div class="forBox">
      <template v-for="(item, index) in carts">
      <div class="shopLis"  :key="index" v-if="item.is_failure == 0">
        <div class="left" v-if="item.goods">
          <img :src="item.goods.thumb" alt="" />
        </div>
        <div class="right" v-if="item.goods">
          <div class="title">{{ item.goods.title }}</div>
          <div class="specification">
            <div class="txt">{{ item.goods_option ? item.goods_option.title : "" }}</div>
            <div class="editCount">
              <div class="cut" @click.stop="CutTap(item)">-</div>
              <van-field v-model="item.total" type="digit" input-align="center" @focus="clickCount(item.total)" @blur="changeCount(item.total, item.id)" />
              <div class="add" @click.stop="AddTap(item, 'cart', index)">+</div>
            </div>
          </div>
        </div>
      </div>
      </template>
    </div>
    <div class="none set-pc-style" v-if="carts.legth <= 0">
      <div class="noneBox">请扫码添加商品</div>
    </div>
    <div class="btn set-pc-style" v-else>
      <div class="left">
        ￥{{ cartsTotal }}
        <div class="txt">(共{{ cartsNum }}件商品)</div>
      </div>
      <div class="right" @click="goodsOrder">去结算</div>
    </div>
    <yz_goodsPopup
      @toOrderChild="toOrderChild"
      @addCart="childAddCart"
      @closeCart="closeCart"
      :themeColor="themeColor"
      :isScanCode="true"
      :goodsInfo="goodsInfo"
      v-model="goodsPopupShow"
      :addCartBtn="false"
    ></yz_goodsPopup>
    <van-popup v-model="addShow" closeable style="width: 17.5rem; height: 15.875rem; border-radius: 0.25rem;" @close="addShow = false">
      <div class="popView">
        <div class="addShowTitle">加入购物车成功</div>
        <img src="https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/storePriceTag%2Fcart.png" alt="" />
        <div class="codeTxt" @click="continueCode">继续扫码</div>
        <div class="cart" @click="closeShowAdd()">查看购物车</div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import yz_goodsPopup from "components/ui_components/yz_goodsPopup";
import { Toast, Dialog } from "vant";
var clicktag = 0;
export default {
  data() {
    return {
      valueNUm: 1,
      goodsInfo: "",
      config: [],
      goodsPopupShow: false,
      store_id: "",
      goodsId: "",
      storeInfo: [],
      carts: [],
      goodsCarts: [],
      cartsNum: 0,
      cartsTotal: 0,
      goodsCartsTotal: "",
      popNum: "",
      goodsCartsOld: "",
      themeColor: "#f14e4e",
      addShow: false
    };
  },
  components: { yz_goodsPopup },
  mounted() {},
  activated() {
    if (this.$route.params.store_id) {
      this.store_id = this.$route.params.store_id;
      this.getStoreInfo();
      // 获取购物车列表
      this.getCart();
    }
    if (this.$route.params.id) {
      this.goodsId = this.$route.params.id;
      this.getGoodsDetail(this.goodsId);
    }
  },
  methods: {
    toOrderChild() {
      if (this.goodsCarts.length <= 0) {
        Toast("购物车暂无商品");
        return;
      }
      this.goodsPopupShow = false;
      this.goodsId = "";
      this.goodsOrder();
    },
    goodsOrder() {
      let val = this.goodsCarts;
      this._goodsOrder(val);
    },
    async _goodsOrder(val, status) {
      if (this.operating_state == 1) {
        Toast("门店休息中");
        return;
      }
      if (await this.checkInviter()) {
        return;
      }
      let sum = 0;
      if (!status && !this.isHasDifferType(val)) {
        return;
      }
      this.carts.forEach(val => {
        sum += val.total;
      });

      if (sum == 0) {
        return;
      }

      // console.log(sum);
      if (val.length == 0 || this.carts.length == 0) {
        return;
      } else {
        this.$router.push(
          this.fun.getUrl(
            "goodsorder",
            {},
            {
              store_id: this.store_id,
              tag: "store"
            }
          )
        );
      }
    },
    //检查是否开启邀请页面
    async checkInviter() {
      if (this.is_invite === -1) {
        let response = await $http.get("member.member.isValidatePageGoods", {});
        if (response.result === 1) {
          this.is_invite = response.data.is_invite;
          if (this.goodsInfo.has_one_invite_page && this.goodsInfo.has_one_invite_page.status === 1 && response.data.is_invite === 0) {
            this.$router.push(this.fun.getUrl("Inviter", {}, { fromGood: 1 }));
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    isHasDifferType(data) {
      //门店购物车提交结算的时候，要判断当前购物车中是否同时存在普通商品和安装服务商品，如果同时存在，要弹框提示
      // 商品不是安装服务商品，直接没有live_install这个字段
      let open_state = 0; //有安装服务的商品
      let clone_state = 0; //没安装服务的商品
      let plugin_name = "";
      data.forEach(item => {
        if (item.live_install && item.live_install.open_state == 1) {
          open_state += 1;
          plugin_name = item.live_install.plugin_name;
        } else {
          clone_state += 1;
        }
      });
      if (open_state != 0 && clone_state != 0) {
        //都有值说明存在 两种 不同商品类型，提示框显示
        Dialog.confirm({
          title: "提示",
          message: `普通商品与${plugin_name}商品一同下单将无法享受${plugin_name}，是否继续下单？`
        })
          .then(() => {
            this._goodsOrder(data, true);
          })
          .catch(() => {});
        return false;
      }
      return true;
    },

    continueCode() {
      this.goodsPopupShow = false;
      this.goodsId = "";
      this.addShow = false;
      this.toScanCode();
    },
    closeShowAdd() {
      this.goodsPopupShow = false;
      this.goodsId = "";
      this.addShow = false;
    },
    childAddCart(e) {
      console.log(e);
      let good = e.goodsInfo;
      let optionsId = e.optionsId;
      let goodsCount = e.goodsCount;
      let exist = null; //用来判断购物车列表是否已经有这个商品规格的
      if (!optionsId) {
        // 单规格
        for (let i = 0; i < this.carts.length; i++) {
          if (this.carts[i].goods_id == good.id) {
            exist = i;
          }
        }
        if (exist == null) {
          //没有规格,并且购物车列表没有这个商品 addCart 只能数量只能加1
          // console.log('并且购物车列表没有这个商品')
          this.addCart(good, "goodPopup", goodsCount, optionsId);
        } else {
          //没有规格,并且购物车列表有这个商品
          // console.log('没有规格,并且购物车列表有这个商品',goodsCount,this.carts[exist].total)
          let addNum = Number(goodsCount) + Number(this.carts[exist].total) - Number(this.carts[exist].total);
          this.updateCartRequest(this.carts[exist].id, addNum, "goodPopup");
        }
      } else {
        // 有规格
        for (let i = 0; i < this.carts.length; i++) {
          if (this.carts[i].option_id == optionsId) {
            exist = i;
          }
        }
        if (exist == null) {
          //有规格 并且购物车列表没有有这个商品
          // console.log('并且购物车列表没有这个商品')
          this.addCart(good, "goodPopup", goodsCount, optionsId);
        } else {
          //有规格,并且购物车列表有这个商品
          // console.log('有规格,并且购物车列表有这个商品',goodsCount,this.carts[exist].total)
          let addNum = Number(goodsCount) + Number(this.carts[exist].total) - Number(this.carts[exist].total);
          this.updateCartRequest(this.carts[exist].id, addNum, "goodPopup");
        }
      }
    },
    getStoreInfo() {
      $http
        .get("plugin.store-cashier.frontend.store.get-store-info.get-stores-details", { store_id: this.store_id }, "")
        .then(response => {
          if (response.result == 1) {
            this.themeColor = JSON.parse(localStorage.getItem("yz_basic_info")).theme_color;
            this.storeInfo = response.data;
            console.log(this.storeInfo);
          } else {
            //轻提示
            this.$dialog.alert({
              message: response.msg
            });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getCart() {
      $http
        .get("plugin.store-cashier.frontend.shoppingCart.member-cart.index", { store_id: this.store_id }, "")
        .then(response => {
          if (response.result == 1) {
            this.getFirstCart(response.data);
            console.log(response.data);
          } else {
            //轻提示
            this.$dialog.alert({
              message: response.msg
            });
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getFirstCart(data) {
      this.carts = data;
      this.goodsCarts = [];
      this.cartsNum = 0;
      this.cartsTotal = 0;
      this.carts.forEach(item => {
        this.$set(this.goodsCarts, item.goods_id, item);
        this.cartsNum += item.total;
        if(item.is_failure == 0){
          this.cartsTotal += item.total * item.goods.price;
        }
      });
      this.goodsCartsTotal = this.calculateTotal(this.carts);
      this.cartsTotal = parseFloat(this.cartsTotal).toFixed(2);
    },
    //不同规格的同一商品求和
    calculateTotal(arr) {
      let newArr = []; // 保存求和后的购物车数量列表
      let temp = {};
      let newArr2 = [];
      for (let i in arr) {
        let key = arr[i].goods_id;
        if (temp[key]) {
          temp[key].total = temp[key].total + arr[i].total; //id相同则把数量相加
        } else {
          temp[key] = {};
          temp[key].goods_id = arr[i].goods_id;
          temp[key].total = arr[i].total;
        }
      }
      for (let k in temp) {
        newArr.push(temp[k]);
      }
      newArr.forEach(item => {
        this.$set(newArr2, item.goods_id, item);
      });
      return newArr2;
    },
    clickCount(data) {
      this.goodsCartsOld = data;
      console.log(this.goodsCartsOld);
      // this.changeCount(data);
    },
    changeCount(data, id) {
      let changeNum = Number(data);
      if (changeNum < 0) {
        Toast("商品数量不能为负数");
        this.getCart();
        return;
      }
      console.log(changeNum, this.goodsCartsOld);
      if (changeNum == this.goodsCartsOld) {
        return;
      }
      if (changeNum < this.goodsCartsOld) {
        let lowerNum = this.goodsCartsOld - changeNum;
        this.updateCart(id, -lowerNum);
      } else if (changeNum > this.goodsCartsOld) {
        let addNum = changeNum - this.goodsCartsOld;
        this.updateCart(id, addNum);
      }
    },
    AddTap(good, tag, index) {
      this.addCart(good, tag);
    },
    CutTap(good) {
      this.updateCartRequest(good.id, "-1");
    },
    addCart(goods, tag, goodsCount, optionsId) {
      let id = "";
      if (tag === "cart") {
        id = goods.goods_id;
      } else {
        id = goods.id;
      }

      $http
        .get(
          "plugin.store-cashier.frontend.shoppingCart.member-cart.store",
          {
            goods_id: id,
            total: tag == "goodPopup" ? goodsCount : 1,
            store_id: this.store_id,
            option_id: tag == "goodPopup" ? optionsId : goods.option_id || 0
          },
          "添加中"
        )
        .then(
          response => {
            if (response.result === 1) {
              console.log(this.carts);
              // if (tag == "cart") {
              //   this.carts[_i].total = Number(goods.total) + 1;
              // }
              if (tag == "goodPopup") {
                this.addShow = true;
              }
              this.getCart(goods);
            } else {
              this.$dialog.alert({ message: response.msg });
            }
          },
          response => {
            //alert('网络错误，请稍后再试！')
          }
        );
    },
    updateCart(id, num, tag) {
      if (num < 0) {
        var total = 0;
        this.carts.forEach(item => {
          if (item.id == id) {
            total = item.total;
          }
        });

        if (total + num < 0) {
          if (clicktag === 0) {
            clicktag = 1;
            this.delItemByCart(id);
            setTimeout(function () {
              clicktag = 0;
            }, 500);
          }
          return;
        }
        if (clicktag === 0) {
          clicktag = 1;
          this.updateCartRequest(id, num, tag);
          setTimeout(function () {
            clicktag = 0;
          }, 500);
        }
      } else {
        if (clicktag === 0) {
          clicktag = 1;
          this.updateCartRequest(id, num, tag);
          setTimeout(function () {
            clicktag = 0;
          }, 500);
        }
      }
    },
    delItemByCart(cart_id) {
      $http
        .get(
          "plugin.store-cashier.frontend.shoppingCart.member-cart.destroy",
          {
            store_id: this.store_id,
            ids: cart_id
          },
          "删除中..."
        )
        .then(response => {
          if (response.result == 1) {
            this.getCart();
            this.popNum--;
          } else {
            this.$dialog.alert({ message: response.msg });
          }
        });
    },
    // 全部清空
    clearCart() {
      let destroyCarts = [];
      this.carts.forEach(item => {
        destroyCarts.push(item.id);
      });
      if(destroyCarts.length <= 0) return
      $http
        .get("plugin.store-cashier.frontend.shoppingCart.member-cart.destroy", {
          store_id: this.store_id,
          ids: destroyCarts
        })
        .then(response => {
          if (response.result == 1) {
            this.getCart();
            this.showCart = false;
            this.popNum = 0;
          } else {
            //alert('无商品');
            this.$dialog.alert({ message: response.msg });
          }
        });
    },
    updateCartRequest(id, num, tag) {
      $http
        .get(
          "plugin.store-cashier.frontend.shoppingCart.member-cart.updateNum",
          {
            id: id,
            num: num,
            store_id: this.store_id
          },
          "加载中"
        )
        .then(
          response => {
            if (response.result == 1) {
              if (num < 0) {
                this.popNum = this.popNum + num;
              } else {
                this.popNum = this.popNum + num;
              }
              if (tag == "goodPopup") {
                this.addShow = true;
              }
              this.getCart();
            } else {
              this.$dialog.alert({ message: response.msg });
              this.getCart();
            }
          },
          response => {}
        );
    },
    closeCart() {
      this.goodsPopupShow = false;
    },
    // 扫条形码获取商品详情
    getGoodsDetail(goodsId) {
      // 92348 2312312312
      this.goodsId = goodsId;
      $http
        .get("plugin.store-price-tag.frontend.goods.get-goods-page", { id: this.goodsId }, "")
        .then(response => {
          if (response.result == 1) {
            if (response.data.get_store_info && response.data.get_store_info.store_id != this.store_id) {
              this.$dialog
                .confirm({ title: "提示", message: `当前商品不属于此门店是否跳转到该门店` })
                .then(() => {
                  this.$router.replace(this.fun.getUrl("storePriceTagIndex", { store_id: response.data.get_store_info.store_id, id: this.goodsId }));
                })
                .catch(() => {
                  that.$router.go(-1);
                });
              return;
            }
            this.goodsInfo = response.data.get_goods;
            this.goodsPopupShow = true;
          } else {
            Toast(response.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    toScanCode() {
      let that = this;
      // that.getGoodsDetail("2312312312");
      if (!this.fun.isWeiXin()) {
        this.$dialog.alert({
          message: "请使用微信浏览器打开"
        });
      } else {
        wx.ready(function () {
          wx.scanQRCode({
            desc: "scanQRCode desc",
            needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
            scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
            success: function (res) {
              console.log("调用扫描成功", res);
              let str = res.resultStr;
              if (str.includes(",")) {
                that.getGoodsDetail(str.split(",")[1]);
              }
            },
            error: function (err) {
              console.log(err);
              //轻提示
              that.$dialog.alert({
                message: "请使用微信浏览器"
              });
            }
          }); //wx.scanQRcode结束
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.none {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  background: #fff;
  padding: 0.25rem 0;
  box-sizing: border-box;

  .noneBox {
    width: 21.88rem;
    height: 2.56rem;
    background: #ccc;
    border-radius: 1.28rem;
    line-height: 2.56rem;
    text-align: center;
    margin: 0 auto;
    color: #fff;
  }
}

.btn {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  padding: 0.25rem 0.81rem 0.25rem 0.75rem;
  justify-content: space-between;
  background: #fff;

  .right {
    width: 6.13rem;
    height: 2.56rem;
    background: var(--color);
    font-size: 0.88rem;
    color: #fff;
    border-radius: 1.28rem;
    text-align: center;
    line-height: 2.56rem;
  }

  .left {
    font-size: 1rem;
    font-weight: bold;
    color: #ef5452;
    line-height: 1.41rem;
    display: flex;
    align-items: center;

    .txt {
      font-size: 0.75rem;
      color: #999;
      margin-left: 0.5rem;
    }
  }
}

.forBox {
  padding-bottom: 4rem;
}

.shopLis:last-child {
  padding-bottom: 0.75rem;
}

.shopLis:first-child {
  padding-top: 0.75rem;
}

.shopLis {
  padding: 0.75rem;
  padding-top: 1.03rem;
  padding-bottom: 0;
  display: flex;
  background: #fff;

  .left {
    flex-shrink: 0;
    width: 3.75rem;
    height: 3.75rem;
    border-radius: 0.13rem;
    margin-right: 0.5rem;

    img {
      width: 100%;
      height: 100%;
      border-radius: 0.13rem;
    }
  }

  .right {
    flex: 1;

    .title {
      font-size: 0.88rem;
      text-align: left;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .specification {
      margin-top: 0.25rem;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 0.75rem;
      color: #999;

      .txt {
        font-size: 0.75rem;
        color: #999;
      }

      .editCount {
        display: flex;

        .cut,
        .add {
          width: 1.5rem;
          height: 1.5rem;
          border: 1px solid #ccc;
          border-radius: 50%;
          color: #000;
          font-size: 1.3rem;
          box-sizing: border-box;
          overflow: hidden;
          line-height: 1.2rem;
        }

        .van-cell {
          padding: 0;
          background: transparent;
          width: 2.22rem;
          text-align: center;
        }

        .van-field__control {
          text-align: center;
        }
      }
    }
  }
}

.shoplistHead {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  box-sizing: border-box;

  .left {
    font-weight: bold;
    font-size: 1rem;
    line-height: 1.41rem;
    font-weight: bold;
  }

  .right {
    display: flex;
    align-items: center;
    font-size: 0.75rem;
    color: #999;
    font-weight: 400;

    img {
      margin-right: 0.25rem;
      width: 0.75rem;
      height: 0.75rem;
    }
  }
}

.codeImg {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding-top: 1.25rem;

  .codeImgBox {
    width: 6.75rem;
    height: 6.75rem;
    border-radius: 100%;
    border: 0.25rem solid #edf2f8;
    background: var(--color);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  img {
    width: 4rem;
    height: 4rem;
    border-radius: 100;
  }

  .txt {
    font-size: 0.88rem;
    line-height: 1.25rem;
    color: #999;
    margin-top: 0.25rem;
  }
}

.scanCode {
  padding: 0.75rem;
  padding-bottom: 1.25rem;
  box-sizing: border-box;
  background: #fff;

  .storeDetail {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    img {
      width: 1.5rem;
      height: 1.5rem;
      border-radius: 50%;
      margin: 0;
      margin-right: 0.38rem;
    }

    .storeName {
      font-weight: bold;
      font-size: 1rem;
    }
  }
}

.popView {
  width: 100%;
  overflow: hidden;
  padding: 1.25rem 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.addShowTitle {
  font-size: 1.125rem;
  color: #333;
  text-align: center;
}

.popView img {
  width: 10.25rem;
  height: 6.125rem;
  margin: 0 auto;
  margin-top: 0.625rem;
}

.popView .codeTxt {
  width: 15rem;
  height: 2.0313rem;
  line-height: 2.0313rem;
  background: var(--color);
  border-radius: 1.0313rem;
  text-align: center;
  font-size: 1.125rem;
  color: #fff;
  margin-top: 1rem;
  margin-bottom: 0.5rem;
}

.popView .cart {
  font-size: 0.875rem;
  color: #999;
  text-align: center;
}
</style>